function varargout = Use_Existing_NRN_Model(varargin)
% USE_EXISTING_NRN_MODEL M-file for Use_Existing_NRN_Model.fig
%      USE_EXISTING_NRN_MODEL, by itself, creates a new USE_EXISTING_NRN_MODEL or raises the existing
%      singleton*.
%
%      H = USE_EXISTING_NRN_MODEL returns the handle to a new USE_EXISTING_NRN_MODEL or the handle to
%      the existing singleton*.
%
%      USE_EXISTING_NRN_MODEL('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in USE_EXISTING_NRN_MODEL.M with the given input arguments.
%
%      USE_EXISTING_NRN_MODEL('Property','Value',...) creates a new USE_EXISTING_NRN_MODEL or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Use_Existing_NRN_Model_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Use_Existing_NRN_Model_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Use_Existing_NRN_Model

% Last Modified by GUIDE v2.5 20-Mar-2007 08:35:10

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Use_Existing_NRN_Model_OpeningFcn, ...
                   'gui_OutputFcn',  @Use_Existing_NRN_Model_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Use_Existing_NRN_Model is made visible.
function Use_Existing_NRN_Model_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Use_Existing_NRN_Model (see VARARGIN)

% Choose default command line output for Use_Existing_NRN_Model
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Use_Existing_NRN_Model wait for user response (see UIRESUME)
% uiwait(handles.using_existing_NRN);


% --- Outputs from this function are returned to the command line.
function varargout = Use_Existing_NRN_Model_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in load_model.
function load_model_Callback(hObject, eventdata, handles)
[filename,directory]=uigetfile('*.nrn','Select tab-delimited text file with data');
if length(filename)==1;if filename==0;return;end;end
set(handles.load_model_msg,'String',' ')
%set(findobj('Tag','background_text'),'String',' ')
set(handles.show_creation_log,'Enable','off')
set(handles.progression_summary,'Enable','off')
set(handles.progress_detail_button,'Enable','off')
set(handles.load_new_data,'Enable','off')
set(handles.generate_template_button,'Enable','off')
set(handles.load_new_data_help_button,'Enable','off')
set(handles.individual_predictions_button,'Enable','off')
set(handles.save_predictions_button,'Enable','off')
set(handles.prediction_txt,'String','Load New data','ForegroundColor','b')
load([directory,filename],'-mat');
set(handles.load_model,'UserData',dt)
pause(0.5)
set(handles.load_model_msg,'String',{filename,' loaded'})
%set(findobj('Tag','background_text'),'String',{'Model Creation Log:',' ','--------------- Model saved --------------------------',dt.log{end:-1:1}})
%show_creation_log_Callback;%(hObject, eventdata, handles);
set(handles.show_creation_log,'Enable','on')
set(handles.progression_summary,'Enable','on')
set(handles.progress_detail_button,'Enable','on')
set(handles.load_new_data,'Enable','on')
set(handles.generate_template_button,'Enable','on')
set(handles.load_new_data_help_button,'Enable','on')

% If teh model comes with predictions, activate those buttons
if isfield(dt,'dt')
    set(handles.individual_predictions_button,'Enable','on')
    set(handles.save_predictions_button,'Enable','on')
    set(handles.prediction_txt,'String',{'TEST:';['variables: ',num2str(length(dt.dt.nx(1,:)))];['samples: ',num2str(length(dt.dt.nx(:,1)))]},'ForegroundColor',[0 0 0.5])
end
%disp(':-)')
% Close old windows
G=get(0);for i=1:length(G.Children);f{i}=G.Children(i);t{i}=get(f{i},'Tag');end
i=[f{strmatch('progress_detail',t,'exact')}]; if ~isempty(i);close(i);end
i=[f{strmatch('use_nrn_main_fig',t,'exact')}]; if ~isempty(i);close(i);end

% Summary descriptive information
set(handles.text_loaded_model,'String',{'TRAINING:';['variables: ',num2str(length(dt.vars))];['samples: ',num2str(length(dt.x(:,1)))];['episodes: ',num2str(length(unique(dt.y)))]})
% find out what windows are open

% Display Summary Info

% hObject    handle to load_model (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in show_creation_log.
function show_creation_log_Callback(hObject, eventdata, handles)
h_main=findobj('Tag','use_nrn_main_fig');gcf0=gcf;
if isempty(h_main);h_main=Use_Existing_NRN_mainFig;end
h_txt=findobj(h_main,'Tag','background_text');h_fig=findobj(h_main,'Tag','main_fig');
set(h_txt,'String',' ','Visible','on');
delete(findobj(h_main,'Type','Axes')); %delete olf axes objects
%set(handles.show_creation_log,'BackgroundColor',[1 1 0.5])
dt=get(findobj('Tag','load_model'),'UserData');
%pause(0.5)
set(h_txt,'String',{'Model Creation Log:',' ','--------------- Model saved --------------------------',dt.log{end:-1:1}})
set(h_main,'Name','Model Creation Summary')
figure(h_main)
figure(gcf0)
%disp(':-)')
% hObject    handle to show_creation_log (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in progression_summary.
function progression_summary_Callback(hObject, eventdata, handles)
%disp(':-)')
h_main=findobj('Tag','use_nrn_main_fig');gcf0=gcf;
if isempty(h_main);h_main=Use_Existing_NRN_mainFig;end
set(h_main,'Name','Progression Summary')
% Remove old graphic handles already
delete(findobj(h_main,'Type','Axes'));
figure(h_main);h_fig=plot(0,0);
h_txt=findobj(h_main,'Tag','background_text');
set(h_txt,'String',' ','Visible','off');set(h_fig,'Visible','on')
dt=get(findobj('Tag','load_model'),'UserData');
neighbor_predict_plot(dt,'survival');
figure(gcf0)
%set(h_txt,'Tag','background_text');set(h_fig,'Tag','main_fig');
%disp(':-)')
% hObject    handle to progression_summary (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in progress_detail_button.
function progress_detail_button_Callback(hObject, eventdata, handles)
gcf0=gcf;
h=findobj('Tag','progress_detail');
if isempty(h);h=Progress_Detail;end
dt=get(handles.load_model,'UserData');
T=[dt.predict(:).T];n=length(T);
h_list=findobj(h,'Tag','progress_list_models');
h_model=findobj(h,'Tag','select_model');
C=cell(n,1);
for i=1:n;C{i}=[num2str(T(i))];end
set(h_list,'String',C);
set(h_model,'UserData',dt)
Progress_Detail_FillGUI(h)

figure(h);figure(gcf0);
% hObject    handle to progress_detail_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes during object creation, after setting all properties.
function using_existing_NRN_CreateFcn(hObject, eventdata, handles)
%disp(':-)')
set(hObject,'Position',[3.4000 10.3846 43 42.1538])
% hObject    handle to using_existing_NRN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called




% --- Executes on button press in load_new_data.
function load_new_data_Callback(hObject, eventdata, handles)
[filename,directory]=uigetfile('*.*','Select new data in tab-delimited format');
if length(filename)==1;if filename==0;return;end;end

% hObject    handle to load_new_data (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
fid=fopen([directory,filename],'r');
linha=fgetl(fid);
set(handles.prediction_txt,'String','Loading ...','ForegroundColor','r')
if length(linha)>=42
    if strcmp(linha(1:42),'DON''T FORGET TO SAVE AS TAB-DELIMITED TEXT')
        linha=fgetl(fid); %then ignore this first line and move to teh next
    end
end
%Collect variable names
vars=eval(['{''',regexprep(linha,'\t',''','''),'''}']);vars(1)=[];
%compare with model
dt=get(handles.load_model,'UserData');
% remove existing predictions if they exist
if isfield(dt,'dt');dt=rmfield(dt,'dt');end
n=length(dt.x(1,:)); % all the x vars
if length(vars)<n %at the very least we need the input variables
    set(handles.prediction_txt,'String',{'Not enough Variables:';['the new data has ',num2str(length(vars)),', ',num2str(n),' were expected.']},'ForegroundColor','r')
    return
    disp(':-O !')
end
dt.dt.vars=vars;%(1:end);
%Check Variable Names
for i=1:length(dt.dt.vars)
    if ~strcmp(dt.vars{i},dt.dt.vars{i})
        set(handles.prediction_txt,'String',{['Var #',num2str(i),': "',dt.dt.vars{i},'" found, "',dt.vars{i},'" expected.']},'ForegroundColor','r')
        return
    end
end

dt.dt.x=[];i=0;
while ~feof(fid)
    i=i+1;linha=fgetl(fid);
    vars=eval(['{''',regexprep(linha,'\t',''','''),'''}']);
    dt.dt.samples{i}=vars{1};
    dt.dt.x=[dt.dt.x;str2num([sprintf('%s,',vars{2:end-1}),vars{end}])];
end
fclose(fid);
if length(dt.dt.x(1,:))==(n+1); % then observed outcomes were included
    dt.dt.y=dt.dt.x(:,end);
    dt.dt.x(:,end)=[];
end
%Now normalize the data just as before
Ind=strmatch('   data loaded from file',dt.log);Ind=Ind(end); %starting by the last event where data was loaded
IndNorm=strmatch('   Quantile normalization',dt.log);IndNorm(find(IndNorm>Ind)); % Identify subsequent normaization steps
% Now apply them to each new entry
set(handles.prediction_txt,'String',{'Normalizing';'new data';'as the training';'data was';'(creation log)'},'ForegroundColor','r')
dt.dt.nx=dt.dt.x; %to initialize the matrix
for i=1:length(dt.dt.x(:,1)) %for each row in the new data set normalize
    for j=1:length(IndNorm) % for each consecutive normalization operation
       switch dt.log{IndNorm(j)}
           case '   Quantile normalization across samples'
               % find quantile of individual variable values with regard to
               % their distribution in the trainign set
               for k=1:length(dt.x(1,:)) % for each value
                   if length(unique(dt.x(:,k)))>2
                   %try
                   [lala,dtk]=memb(dt.x(:,k));
                   dt.dt.nx(i,k)=memb(dt.dt.x(i,k),dtk);
                   %catch
                   %    disp(':-O')
                   %end
                   end
               end
           case '   Quantile normalization across variables'
               dt.dt.nx(i,:)=memb(dt.dt.x(i,:));
       end
        
    end        
end
% Make predictions
for i=1:length(dt.predict) % for each predictive model
    dti=dt;dti.predict=dti.predict(i);
    [lala,dt.dt.predict(i)]=neighbor_predict(dti,dt.dt.nx);
    %dt.dt.predict(i).T=dti.predict.T;
end
for i=1:length(dt.predict) % for each predictive model
    dt.dt.predict(i).T=dt.predict(i).T;
end

% And finish by generating summary predictions back to dt
T=[dt.dt.predict.T]; % for each possible outcome
for j=1:length(T)
    dt.dt.predict(j).py=mean(dt.dt.predict(j).y,2);
    %try
    %dt.dt.predict(j).py=mean(dt.dt.predict(j).y(:,1:dt.dt.predict(j).OptN)<=dt.dt.predict(j).T,2);
    %catch
     %   %there were some variables with no change in value
     %   %dt.dt.predict(j).py=mean(dt.dt.predict(j).y<=dt.dt.predict(j).T,2);
    %disp(':-O')
    %end
end
dt.dt.T=T;
dt.dt.Y=[dt.dt.predict.py];
    
%disp(':-)')
set(handles.load_model,'UserData',dt);
set(handles.individual_predictions_button,'Enable','on')
set(handles.save_predictions_button,'Enable','on')

set(handles.prediction_txt,'String',{filename;['variables: ',num2str(length(dt.dt.nx(1,:)))];['samples: ',num2str(length(dt.dt.nx(:,1)))]},'ForegroundColor',[0 0 0.5])

        
        




% --- Executes on button press in load_new_data_help_button.
function load_new_data_help_button_Callback(hObject, eventdata, handles)
load_new_data_help;
% hObject    handle to load_new_data_help_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in generate_template_button.
function generate_template_button_Callback(hObject, eventdata, handles)
[filename,directory]=uiputfile('*.*','Name tab-delimited text file template');
fid=fopen([directory,filename,'.xls'],'w');
fprintf(fid,'%s','DON''T FORGET TO SAVE AS TAB-DELIMITED TEXT, also note that you don''t have to fill the known outcome column (the last one) but if you do you will be able to use the validation tools to compare observed with predicted values.');
dt=get(handles.load_model,'UserData');
fprintf(fid,'\n%s\t','Sample_ID');
fprintf(fid,'%s\t',dt.vars{1:length(dt.x(1,:))+1});
%disp(':-)')
fclose(fid);
system(['explorer ',directory,filename,'.xls']);
%web([directory,filename,'.xls'])
%
% hObject    handle to generate_template_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in individual_predictions_button.
function individual_predictions_button_Callback(hObject, eventdata, handles)

h=individual_predictions;
dt=get(handles.load_model,'UserData');
set(h,'UserData',dt);
h_handles=guihandles(h);
set(h_handles.select_sample,'String',dt.dt.samples);
individual_predictions_fillGUI(h);

% hObject    handle to individual_predictions_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in save_predictions_button.
function save_predictions_button_Callback(hObject, eventdata, handles)
% hObject    handle to save_predictions_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%disp(':-)')
dt=get(handles.load_model,'UserData');

[filename, pathname, filterindex]=uiputfile({'*.nrn','(*.nrn) Saves Model with predictions';'*.txt','(*.txt) Saves only predictions, tab-delimited';'*.xls','(*.xls) Saves and opens in Excel'},'Save as');
%disp(':-)')
switch filterindex
    case 1 % nrn
        filename=[regexprep(filename,'\.\w*',''),'.nrn'];
        save([pathname,filename],'dt')
        %set(gcf,'PaperPositionMode','auto');
        %print('-dpdf',[pathname,filename]);
    case 2 % tab-delimited
        filename=[regexprep(filename,'\.\w*',''),'.txt'];
        fid=fopen([pathname,filename],'w');
        %fprintf(fid,'%s\n','Committee voting for available outcomes (column headers):')
        %fprintf(fid,'%s\n',['Sample ID',sprintf('\t%f',dt.dt.T)]);
        for i=1:length(dt.dt.samples)
            fprintf(fid,'%s\n',[sprintf('\t%f',dt.dt.Y(i,:))]);
        end
        fclose(fid);
     case 3 % tab-delimited
        filename=[regexprep(filename,'\.\w*',''),'.xls'];
        fid=fopen([pathname,filename],'w');
        fprintf(fid,'%s\n','Committee voting for available outcomes:');
        fprintf(fid,'%s\n',['Value:',sprintf('\t%f',dt.dt.T)]);
        for i=1:length(dt.dt.samples)
            fprintf(fid,'%s\n',[dt.dt.samples{i},sprintf('\t%f',dt.dt.Y(i,:))]);
        end
        fclose(fid);
        system(['explorer ',pathname,filename]);
        %hgsave([pathname,filename]); 
end
    
    
% Save predictions as tab-delimited file or as nrn file




% --- Executes on button press in validation_button.
function validation_button_Callback(hObject, eventdata, handles)
% hObject    handle to validation_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in model_report_button.
function model_report_button_Callback(hObject, eventdata, handles)
% hObject    handle to model_report_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in prediction_report_button.
function prediction_report_button_Callback(hObject, eventdata, handles)
% hObject    handle to prediction_report_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in help_validation.
function help_validation_Callback(hObject, eventdata, handles)
% hObject    handle to help_validation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


